<template>
  <div id="login">
    <el-form ref="form" status-icon :model="form" label-width="80px" :rules="rules">
      <img class="buddha" src="../assets/logo.png" alt />
      <el-form-item label="用户名" prop="username">
        <el-input @keyup.enter.native="login" v-model="form.username" placeholder="请输入用户名"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input @keyup.enter.native="login" type= 'password' v-model="form.password" placeholder="请输入密码"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="login" class="loginBtn">登录</el-button>
        <el-button @click="reset">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>

export default {
  data () {
    return {
      // 双向绑定
      form: {
        username: '',
        password: ''
      },
      // 表单校验
      rules: {
        // 用户名校验
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          {
            min: 3,
            max: 12,
            message: '长度在 3 到 12 个字符',
            trigger: ['change', 'blur']
          }
        ],
        // 密码校验
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          {
            min: 6,
            max: 18,
            message: '长度在 6 到 18 个字符',
            trigger: ['change', 'blur']

          }
        ]
      }
    }
  },
  methods: {
    reset () {
      this.$refs.form.resetFields()
    },
    login () {
      this.$refs.form.validate(isValid => {
        // console.log(this.$refs.form.validate)

        if (!isValid) return
        this.$axios
          .post('login', this.form)
          .then(res => {
            const { meta, data } = res

            if (meta.status === 200) {
              console.log(meta.msg)
              this.$message({
                message: meta.msg,
                type: 'success'
              })
              localStorage.setItem('token', data.token)
              this.$router.push('/index')
            } else {
              this.$message.error(meta.msg)
            }
          })
      })
    }
  }
}
</script>

<style lang = 'less' scoped>
#login {
  background-color: #2d434c;
  width: 100%;
  height: 100%;
  overflow: hidden;
  .el-form {
    width: 400px;
    margin: 0 auto;
    margin-top: 200px;
    background-color: #fff;
    padding: 70px 30px 30px;
    position: relative;
    .loginBtn {
      margin-right: 70px;
    }
    .buddha {
      width: 80px;
      position: absolute;
      left: 50%;
      transform: translate(-50%);
      top: -35px;
    }
  }
}
</style>
